<template src="./resource-center.html"></template>

<script>
import Bus from "@/utils/event_bus";
import axios from "axios";
import resourceCenterConfig from "@/config/resourceCenter.js";
import config from "@/config/tjConfig.js";
import { formatDate } from "@/utils/tjDate.js";
import qs from "qs";
import debounce from "lodash.debounce";
import Scrollbar from "smooth-scrollbar";
export default {
  name: "resource-center",
  data() {
    let data = {
      activeName: "first",
      searchInput: "",
      dynamicTags: [],
      // dynamicTags: [{
      //     group: "来源分类",
      //     tag: "公共资源",
      //     code: "0"
      // }],
      total: 0,
      curPage: 1,
      sortField: "updatedAt",
      //secondCategoryList: resourceCenterConfig.secondCategoryList,
      secondCategoryList: [],
      dataList: [],
      mapDialogVisible: false,
      resourceApplydialogVisible: false,
      map: null,
      curFirstCategory: "数据资源",
      uploadDialogVisible: false,
      dialogImageUrl: "",
      resourceAuthorityOptions: [
        {
          value: "3",
          label: "个人使用"
        },
        {
          value: "2",
          label: "群组使用",
          children: []
        },
        {
          value: "1",
          label: "部门使用",
          children: []
        }
      ],
      selectedResourceAuthorityOptions: [],

      preApplyResList: [],
      multipleSelection: [],
      fileList: [],

      resApplyFormData: {
        title: "",
        comment: "",
        type: 0,
        resIdArr: []
      },
      searchAppliedInput: "",
      // approveStatusList:{
      //     '0':'预申请',
      //     '1':'待审核',
      //     '2':'已通过',
      //     '3':'未通过'
      // },
      ownerTypeList: {
        "1": "deptName",
        "2": "groupName",
        "3": "userName"
      },
      appliedList: [],
      hasNext: true,
      sortType: "DESC",
      resDuplicateList: [],
      dataDescribeTableData: [],
      fieldDescribeTableData: [],
      // selectedResItem:null,
      mapPreviewVisible: true
    };
    return data;
  },
  mounted() {
    this.init();
    this.query();
    this.handleScrollbar();

    this.$nextTick(() => {
      // let height = document.documentElement.clientHeight - 200;
      // console.log(height);
      // document.querySelector('.map-dialog').style.height = height + 'px';
    });
    this.$emit("on-view-load");
  },
  filters: {
    formatDate(time, type) {
      let date = new Date(time);
      let str = formatDate(date, "yyyy-MM-dd hh:mm");
      if (type == "date") {
        str = formatDate(date, "yyyy-MM-dd");
      }
      return str;
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    }
    // resAuthority(){
    //     return resourceItem[this.ownerTypeList[resourceItem.ownerType]]
    // }
  },
  methods: {
    init() {
      this.requestSecondCategory();
    },
    requestSecondCategory() {
      let url = `${config.api}/resource/query/count/-1`;
      axios.get(url).then(response => {
        //console.log(response);
        let data = response.data.data;
        for (let index in data) {
          let arr = data[index];
          arr.sort((a, b) => {
            return b.count - a.count;
          });
        }
        let groupList = {
          "0": "来源分类",
          "1": "权限分类",
          "2": "主题分类",
          "3": "服务机构",
          "4": "审核状态"
        };
        let secondCategoryList = [];
        for (let index in data) {
          if (groupList[index] == "审核状态") {
            continue;
          }
          let item = {
            group: groupList[index],
            list: data[index]
          };
          if (item.group == "来源分类") {
            let publicResource = item.list.find(element => {
              return element.name == "公共资源";
            });
            // publicResource.active = true;
            item.list = item.list.filter(element => element.name != "个人资源");
          }
          if (["主题分类", "服务机构"].includes(groupList[index])) {
            item.collapse = true;
          }
          secondCategoryList.push(item);
        }
        this.secondCategoryList = secondCategoryList;
      });
    },
    //处理checkbox选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //console.log(this.multipleSelection);
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClick(tab, event) {
      //console.log(tab, event);
    },
    handleTagClose(item) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(item), 1);
      //移除高亮
      let dlList = this.$el.querySelectorAll(".second-category dl");
      for (let dlDom of dlList) {
        let group = dlDom.querySelector("dt").innerText;
        if (group == item.group) {
          let ddList = dlDom.querySelectorAll("dd");
          for (let ddDom of ddList) {
            //let tag = ddDom.innerText.replace(/^\s+|\s+$/g,"");
            let tag = ddDom
              .querySelector("span")
              .innerText.replace(/^\s+|\s+$/g, "");
            if (tag == item.tag) {
              ddDom.classList.remove("second-category-active");
            }
          }
        }
      }
      this.query();
    },
    firstCategoryClick(name, event) {
      //console.log(name);
      let arr = ["预申请资源", "已申请资源"];
      if (!this.userInfo && arr.includes(name)) {
        this.$message.error("只有登录用户才可以查看！");
        return;
      }

      let list = this.$el.querySelectorAll("ul.first-category li");
      for (let item of list) {
        item.classList.remove("first-category-active");
      }
      event.currentTarget.classList.add("first-category-active");
      this.curFirstCategory = name;
      Bus.$emit("UPDATE_RESOURCECENTER_PATH", this.curFirstCategory);
      if (this.curFirstCategory == "数据资源") {
        //初始化
        this.query();
      } else if (this.curFirstCategory == "预申请资源") {
        this.dynamicTags = [];
        let dlList = this.$el.querySelectorAll(".second-category dl");
        for (let dlDom of dlList) {
          let group = dlDom.querySelector("dt").innerText;
          let ddList = dlDom.querySelectorAll("dd");
          for (let ddDom of ddList) {
            ddDom.classList.remove("second-category-active");
          }
        }
        //初始化
        this.query();
      } else if (this.curFirstCategory == "已申请资源") {
        this.queryAppliedRes();
      }
    },
    secondCategoryClick(item, event) {
      //console.log(item);
      let arr = ["部门资源", "群组资源"];
      if (!this.userInfo && arr.includes(item.name)) {
        this.$message.error("只有登录用户才可以查看！");
        return;
      }
      let currentTarget = event.currentTarget;
      let group = currentTarget.parentNode.getElementsByTagName("dt")[0]
        .innerText;
      let tag = item.name;
      //移除高亮
      let list = currentTarget.parentNode.querySelectorAll("dd");
      for (let item of list) {
        item.classList.remove("second-category-active");
      }
      //添加高亮
      currentTarget.classList.add("second-category-active");
      //判断同组同tag
      let element = this.dynamicTags.find((item, index) => {
        return item.group == group && item.tag == tag;
      });
      if (element) {
        return;
      }
      //判断同组不同tag
      for (let i = 0; i < this.dynamicTags.length; i++) {
        let item = this.dynamicTags[i];
        if (item.group == group) {
          this.dynamicTags.splice(i, 1);
          i--;
        }
      }
      this.dynamicTags.push({
        group: group,
        tag: tag,
        code: item.code
      });
      //console.log(this.dynamicTags);
      this.query();
    },
    handleLoadMore(item, event) {
      let group = item.group || item;
      if (group == "主题分类" || group == "服务机构") {
        let currentTarget = event.currentTarget;
        let iconfontDom = currentTarget.querySelector(".iconfont");
        if (iconfontDom) {
          if (iconfontDom.classList.contains("icon-light-arrow-down")) {
            iconfontDom.classList.remove("icon-light-arrow-down");
            iconfontDom.classList.add("icon-light-arrow-up");
          } else {
            iconfontDom.classList.remove("icon-light-arrow-up");
            iconfontDom.classList.add("icon-light-arrow-down");
          }
        }
        item.collapse = !item.collapse;
      } else if (
        group == "数据资源" ||
        group == "预申请资源" ||
        group == "已申请资源"
      ) {
        this.loadMoreFun();
      }
    },
    loadMoreFun() {
      this.curPage++;
      this.query("loadMore");
    },
    query(type) {
      if (type != "loadMore") {
        this.curPage = 1;
        this.dataList = [];
        this.preApplyResList = [];
      }
      let queryParams = {
        status: 0, //查询所有资源
        params: {
          // ownerType: "0",
          sort: this.sortField,
          rows: 30,
          page: this.curPage,
          order: this.sortType
        }
      };
      if (this.curFirstCategory == "预申请资源") {
        queryParams = {
          status: 1, //查询所有资源
          params: {
            sort: this.sortField,
            rows: 30,
            page: this.curPage,
            order: this.sortType
          }
        };
      }

      if (this.searchInput != "") {
        queryParams.params.name = this.searchInput;
      }
      this.dynamicTags.forEach(item => {
        if (item.group == "来源分类") {
          queryParams.params.ownerType = item.code;
        } else if (item.group == "权限分类") {
          queryParams.params["apply"] = item.code;
        } else if (item.group == "主题分类") {
          queryParams.params["resClsId"] = item.code;
        } else if (item.group == "服务机构") {
          queryParams.params["deptId"] = item.code;
        } else if (item.group == "审核状态") {
          queryParams.params["approveStatus"] = item.code;
        }
      });
      let url = `${config.api}/resource/center/query/${queryParams.status}`;
      // this.dataList=[];
      this.$root.$http
        .get(url, {
          params: queryParams.params
        })
        .then(response => {
          // console.log(response);
          this.total = response.data.total;
          let data = response.data;
          let list = [];
          data.data.forEach(element => {
            let imgUrl = `${config.host}/s/public_data/${element.ghid}/thumb`;
            let item = {
              id: element.resId,
              img: imgUrl,
              name: element.name,
              publishingUnit: element.groupName || element.deptName,
              viewCount: element.viewCount,
              praiseCount: element.praiseCount,
              applyCount: element.applyCount
            };
            Object.assign(element, item);
            list.push(element);
          });
          if (this.curFirstCategory == "数据资源") {
            this.dataList = [
              ...this.dataList,
              ...JSON.parse(JSON.stringify(list))
            ];
            // console.log(this.dataList);
            // this.handleScrollbar();
          } else if (this.curFirstCategory == "预申请资源") {
            this.preApplyResList = [
              ...this.preApplyResList,
              ...JSON.parse(JSON.stringify(list))
            ];
          }
          this.hasNext = 30 * this.curPage > data.total ? false : true;
          this.handleScrollbar();
          // console.log(this.hasNext);
          // this.$nextTick(()=>{
          //     this.handleScrollbar();
          // });
        });
    },

    handelResPreApply(item) {
      if (item.preApplyId) {
        this.$message.error("您已经预申请过该数据资源，不能重复预申请！");
        return;
      }
      let url = `${config.api}/resourceApply/add/pre/${item.resId}`;
      axios.get(url).then(response => {
        // console.log(response);
        if (response.data.data.preApplyId) {
          item.preApplyId = response.data.data.preApplyId;
          this.$message.success("预申请成功！");
        }
      });
    },
    handleClearSelected() {
      this.dynamicTags = [];
      let dlList = this.$el.querySelectorAll(".second-category dl");
      for (let dlDom of dlList) {
        let group = dlDom.querySelector("dt").innerText;
        let ddList = dlDom.querySelectorAll("dd");
        for (let ddDom of ddList) {
          ddDom.classList.remove("second-category-active");
        }
      }
      this.query();
    },
    handlePreview(item) {
      this.mapDialogVisible = true;
      this.addResView(item);
      this.$nextTick(() => {
        this.initMap(item);
        this.showMetaDataInfo(item);
      });
    },
    addResView(item) {
      let url = `${config.api}/resource/view/add/${item.resId}`;
      this.$root.$http.get(url).then(response => {
        //console.log(response);
        if (response.data.success) {
          item.viewCount++;
        }
      });
    },
    handleImgMouseover(item, event) {
      event.currentTarget.parentNode.querySelector(".img-mask").style.display =
        "block";
    },
    handleImgMouseout(item, event) {
      event.currentTarget.parentNode.querySelector(".img-mask").style.display =
        "none";
    },
    initMap(item) {
      if (!this.map) {
        this.map = new G.Map("map-container", {
          maxRes: 19567.879241,
          recordStatus: false,
          pinchRotate: false,
          continuouslyZoom: false,
          hideLogo: true,
          initStatus: {
            pitch: 50,
            center: [13047994, 4736323],
            res: 611.49622628125
          }
        });
        console.log("1");
        console.log(this.map);
        let zoomControl = new G.Control.Zoom({
          position: "top-right"
        });
        this.map.addControl(zoomControl);
        //添加底图
        this.addBasemap();
      }

      let queryParams = {
        dataUid: item.ghid,
        name: item.name,
        extent: JSON.parse(item.extent),
        geometryType: item.geometryType,
        ownerType: item.ownerType
      };
      this.map.zoomExtent(queryParams.extent);
      this.setLayer(queryParams);
    },
    addBasemap() {
      console.log(config.basemap);
      console.log(this.map);
      let basemapLayer = null;
      // if (config.basemap.type == "google") {
      //   basemapLayer = new G.Layer.GoogleCnMap("street");
      if (config.basemap.type == "tianditu") {
        basemapLayer = new G.Layer.Tile(
          "http://{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEROW={y}&TILECOL={x}&TILEMATRIX={z}&tk=8f1fd352c177be5952e6df95575a8318",
          {
            cluster: ["t0", "t1", "t2", "t3"]
          }
        );
      } else {
        basemapLayer = new G.Layer.Tile(config.basemap.vector);
      }
      basemapLayer.options.name = "basemap";
      basemapLayer.options.basemapType = "vector";
      this.map.addLayer(basemapLayer);
      let tiledLayer = new G.Layer.Tile("", {
        name: "previewLayer"
      });
      tiledLayer.addTo(this.map);
    },
    setLayer(queryParams) {
      let layer = this.getLayerByName("previewLayer");
      layer.setUrl("");

      let url = `${config.host}/s/dataviz/config`;
      // let url = `http://localhost:9600/s/dataviz/config`;
      let configJsonItem = {};
      if (["pt", "mpt"].includes(queryParams.geometryType)) {
        configJsonItem = JSON.parse(JSON.stringify(config.configJson.pt));
      } else if (["pl", "mpl"].includes(queryParams.geometryType)) {
        configJsonItem = JSON.parse(JSON.stringify(config.configJson.pl));
      } else if (["pg", "mpg"].includes(queryParams.geometryType)) {
        configJsonItem = JSON.parse(JSON.stringify(config.configJson.pg));
      } else {
        this.$message.error("几何类型未知！");
        return;
      }
      configJsonItem.dataUid = queryParams.dataUid;
      // if(queryParams.ownerType == "0"){
      //     configJsonItem.dataType = 'public';
      // }
      // configJsonItem.dataType = 'public';
      // console.log(configJsonItem);

      let configJson = [configJsonItem];
      let params = {
        configJson: JSON.stringify(configJson)
      };
      axios.post(url, qs.stringify(params)).then(response => {
        let vizId = response.data.data.vizId;

        let vizUrl = `${config.host}/s/dataviz/${vizId}/{z}/{x}/{y}.png?retina={i}`;
        layer.setUrl(vizUrl);
      });
    },
    getLayerByName(name) {
      let layers = this.map.getLayers();
      let _layer = null;
      for (let index in layers) {
        let layer = layers[index];
        if (layer.options.name == name) {
          _layer = layer;
          break;
        }
      }
      return _layer;
    },
    // datavizRequest(){
    //     let url = `${config.host}/s/data/e51ac36474f9464e8a8f26eea08d5457/query`;
    //     axios.get(url).then((response)=>{
    //         console.log(response);
    //     });
    // },
    switchBasemap() {
      let basemapLayer = this.map.getLayerByName("basemap");
      let basemapType = basemapLayer.options.basemapType;
      if (basemapLayer) {
        basemapLayer.remove();
      }
      if (basemapType == "vector") {
        if (config.basemap.type == "tianditu") {
          basemapLayer = new G.Layer.Tile(
            "http://{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEROW={y}&TILECOL={x}&TILEMATRIX={z}&tk=8f1fd352c177be5952e6df95575a8318",
            {
              cluster: ["t0", "t1", "t2", "t3"]
            }
          );
        } else {
          basemapLayer = new G.Layer.Tile(config.basemap.imagery);
        }
        basemapLayer.options.basemapType = "imagery";
      } else if (basemapType == "imagery") {
        if (config.basemap.type == "tianditu") {
          basemapLayer = new G.Layer.Tile(
            "http://{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEROW={y}&TILECOL={x}&TILEMATRIX={z}&tk=8f1fd352c177be5952e6df95575a8318",
            {
              cluster: ["t0", "t1", "t2", "t3"]
            }
          );
        } else {
          basemapLayer = new G.Layer.Tile(config.basemap.vector);
        }
        basemapLayer.options.basemapType = "vector";
      }
      basemapLayer.options.name = "basemap";
      this.map.addLayer(basemapLayer);
      basemapLayer.bringToBottom();
    },
    showMetaDataInfo(item) {
      console.log("showmetadatainfo");
      // let dataUid = this.selectedResItem.ghid;
      let dataUid = item.ghid;

      let url = `${config.host}/s/public_data/${dataUid}/info`;
      this.dataDescribeTableData = [];
      this.fieldDescribeTableData = [];
      this.$root
        .$http(url)
        .then(response => {
          console.log(response);
          let metadata = "";
          let metadataFlag = true;
          if (response.data.data.metadata == null) {
            metadata = response.data.data.fields;
            metadataFlag = false;
          } else {
            metadata = JSON.parse(response.data.data.metadata);
            metadataFlag = false;
          }

          console.log(metadata);

          let dataDescribeTableData = [];
          let itemConfig = [
            {
              label: "数据来源",
              name: "source"
            },
            {
              label: "数据分类",
              name: "category"
            },
            {
              label: "数据内容",
              name: "content"
            },
            {
              label: "数据数量",
              name: "count"
            },
            {
              label: "数据质量",
              name: "quality"
            },
            {
              label: "创建时间",
              name: "createdAt"
            },
            {
              label: "数据时效",
              name: "aging"
            },
            {
              label: "更新频率",
              name: "frequency"
            },
            {
              label: "覆盖区域",
              name: "admin"
            },
            {
              label: "数据标签",
              name: "tags"
            }
          ];
          if (!metadataFlag) {
            itemConfig.forEach(item => {
              if (item.name == "source") {
                dataDescribeTableData.push({
                  label: item.label,
                  value: "公共数据"
                });
              } else if (item.name == "count") {
                dataDescribeTableData.push({
                  label: item.label,
                  value: response.data.data.count
                });
              } else if (item.name == "createdAt") {
                dataDescribeTableData.push({
                  label: item.label,
                  value: new Date(response.data.data.createdAt).toLocaleString()
                });
              } else {
                dataDescribeTableData.push({
                  label: item.label,
                  value: ""
                });
              }
            });
          } else {
            for (let key in metadata) {
              let tempItem = itemConfig.find(item => item.name == key);
              if (tempItem) {
                if (key == "source" && metadata[key] == "geohey") {
                  metadata[key] = "公共数据";
                }
                dataDescribeTableData.push({
                  label: tempItem.label,
                  value: metadata[key]
                });
              }
            }
          }

          this.dataDescribeTableData = dataDescribeTableData;
          console.log("dataDescribeTableData");
          console.log(this.dataDescribeTableData);

          let fieldDescribeTableData = [];
          let fields = metadata;
          if (metadataFlag) {
            fieldDescribeTableData = metadata;
          } else {
            // for (let key in fields) {
            //   fields[key].name = key;
            //   fieldDescribeTableData.push(fields[key]);
            // }
            metadata.forEach(e => {
              fieldDescribeTableData.push({ name: e.name, type: e.type });
            });
          }

          this.fieldDescribeTableData = fieldDescribeTableData;

          console.log(this.fieldDescribeTableData);
          this.$nextTick(() => {
            Scrollbar.init(document.querySelector("#metaData-container"));
          });
        })
        .catch(error => {
          // this.$message.error(error);
        });
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.uploadDialogVisible = true;
    },
    handleResourceAuthorityChange(name) {
      this.resDuplicateList = [];

      let resAuthority = this.selectedResourceAuthorityOptions;
      if (resAuthority.length <= 1 && resAuthority[0] != "3") {
        this.selectedResourceAuthorityOptions = [];
        return;
      }

      let url = `${config.api}/resourceApply/check`;
      let params = {
        title: "test",
        ownerType: parseInt(resAuthority[0]),
        ownerId: resAuthority[resAuthority.length - 1],
        resId: this.resApplyFormData.resId,
        type: this.resApplyFormData.type
      };

      this.$root.$http.post(url, qs.stringify(params)).then(response => {
        // console.log(response);
        if (!response.data.success) {
          this.selectedResourceAuthorityOptions = [];
          this.resDuplicateList = response.data.data;
        }
      });
    },
    handleCascaderFocus() {
      //this.isFirstLoadCascader = false;
      if (this.isFirstLoadCascader) {
        return;
      } else {
        this.isFirstLoadCascader = true;
      }
      this.$root.$http
        .all([
          this.$root.$http.get(`${config.api}/user/group`),
          this.$root.$http.get(`${config.api}/user/dept`)
        ])
        .then(
          axios.spread((group, dept) => {
            // console.log(group, dept);
            let groupList = group.data.data;
            groupList.forEach(group => {
              this.resourceAuthorityOptions[1].children.push({
                value: group.groupId,
                label: group.groupName
              });
            });
            let deptList = [];
            this.traversalDept(dept.data.data[0], deptList);
            this.resourceAuthorityOptions[2].children = deptList;
          })
        );
    },
    traversalDept(tree, deptList) {
      tree.value = tree.id;
      deptList.push({
        value: tree.value,
        label: tree.label
      });
      if (tree.children) {
        tree.children.forEach(item => {
          this.traversalDept(item, deptList);
          // console.log(item);
        });
      }
    },
    // traversalDept(tree){
    //     tree.value = tree.id;
    //     if(!tree.children){
    //         delete tree.children;
    //         return;
    //     }else{
    //         tree.children.forEach((item)=>{
    //             this.traversalDept(item);
    //             console.log(item);
    //         });
    //     }
    // },
    deletePreApplyRow(index, rows) {
      this.$confirm("确定要移除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let item = rows[index];
          let url = `${config.api}/resourceApply/delete/pre/${item.preApplyId}`;
          this.$root.$http(url, {}).then(response => {
            console.log(response);
            if (response.data.success) {
              rows.splice(index, 1);
              this.$message.success("移除成功。");
            }
          });
        })
        .catch(() => {});
    },
    searchInputChange() {
      //console.log(this.searchInput);
      this.query();
    },
    handleSort(sortField, event) {
      let activeFlag = event.currentTarget.classList.contains("sort-active");
      if (activeFlag) {
        let sortTypeDom = event.currentTarget.querySelector(".iconfont");
        let flag = sortTypeDom.classList.contains("icon-paixu");
        if (flag) {
          sortTypeDom.classList.remove("icon-paixu");
          sortTypeDom.classList.add("icon-shengxu");
          this.sortType = "ASC";
        } else {
          sortTypeDom.classList.remove("icon-shengxu");
          sortTypeDom.classList.add("icon-paixu");
          this.sortType = "DESC";
        }
      }

      let parentNode = event.currentTarget.parentNode;
      let liList = parentNode.querySelectorAll("li");
      for (let item of liList) {
        item.classList.remove("sort-active");
      }
      event.currentTarget.classList.add("sort-active");
      this.sortField = sortField;

      this.query();
    },
    handleUploadPreview() {},
    handleUploadRemove() {},
    handleUploadChange(file, fileList) {
      //console.log(file, fileList);
      // // var fileValue = this.$el.querySelector('.el-upload .el-upload__input').files;
      // // console.log(fileValue);
      // // console.log(this.fileList);
      this.uploadFiles = fileList;
    },
    handleResApply(name, item) {
      //判断用户是否登录
      if (!this.userInfo || !this.userInfo.token) {
        this.$message({
          message: "您未登录，不能使用此功能！",
          type: "warning"
        });
        return;
      }

      this.resApplyFormData.resIdArr = [];
      this.resApplyFormData.nameArr = [];
      if (name == "申请资源") {
        this.resApplyFormData.resId = item.resId;
        this.resApplyFormData.type = 0;
        this.resApplyFormData.nameArr.push(item.name);
      } else if (name == "预申请资源") {
        if (item.length <= 0) {
          this.$message.error("请先选择预申请资源！");
          return;
        }
        let resIdArr = [];
        item.forEach(element => {
          resIdArr.push(element.resId);
          this.resApplyFormData.nameArr.push(element.name);
        });
        this.resApplyFormData.resId = resIdArr.join(",");
        this.resApplyFormData.type = 1;
        //console.log(this.resApplyFormData);
      }
      this.resourceApplydialogVisible = true;
    },
    //资源申请提交
    handleResApplySubmit(multipleSelection) {
      if (this.resApplyTitle == "") {
        this.$message({
          message: "申请标题不能空！",
          type: "error"
        });
        return;
      }
      /*
      let resAuthority = this.selectedResourceAuthorityOptions;
      if (resAuthority.length <= 0) {
        this.$message({
          message: "请选择资源权限！",
          type: "error"
        });
        return;
      }
      */

      if (this.uploadFiles.length <= 0) {
        this.$message({
          message: "请上传证明材料！",
          type: "error"
        });
        return;
      }

      let fd = new window.FormData();
      fd.append("title", this.resApplyFormData.title);
      fd.append("resId", this.resApplyFormData.resId);
      fd.append("type", this.resApplyFormData.type);

      fd.append("ownerType", 1);
      fd.append("ownerId", "0");

      this.uploadFiles.forEach(item => {
        fd.append("attachFile", item.raw);
      });
      fd.append("nt", this.resApplyFormData.comment);

      let url = `${config.api}/resourceApply/add`;
      this.$root.$http
        .post(url, fd, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(response => {
          console.log(response);
          if (response.data.success) {
            this.resourceApplydialogVisible = false;
            this.$message.success("申请成功！");
            if (this.resApplyFormData.type == 1) {
              let resIdArr = this.resApplyFormData.resId.split(",");

              for (let i = 0; i < this.preApplyResList.length; i++) {
                let item = this.preApplyResList[i];
                for (let index2 in resIdArr) {
                  if (item.resId == resIdArr[index2]) {
                    this.preApplyResList.splice(i, 1);
                    i--;
                  }
                }
              }
            }
          } else {
            this.$message.error(response.data.message);
          }
        });
    },
    handleImgError(item) {
      item.img = "static/images/data_resource.png";
    },
    handleResApplyDialogClose() {
      this.fileList = [];
      this.selectedResourceAuthorityOptions = [];
      this.resApplyFormData = {
        title: "",
        comment: "",
        type: 0,
        resIdArr: [],
        nameArr: []
      };
      this.resDuplicateList = [];
    },
    searchAppliedInputChange() {
      this.queryAppliedRes();
    },
    queryAppliedComment(item) {
      this.$alert(item.nt, item.title + "备注", {
        confirmButtonText: "确定",
        callback: action => {
          // this.$message({
          //     type: 'info',
          //     message: `action: ${ action }`
          // });
        }
      });
    },
    queryAppliedRes() {
      let params = {
        rows: 30
      };
      if (this.searchAppliedInput != "") {
        params.title = this.searchAppliedInput;
        //params.name = this.searchAppliedInput;
      }
      let url = `${config.api}/resourceApply/query/order`;
      this.$root.$http
        .get(url, {
          params: params
        })
        .then(response => {
          // console.log(response);

          let data = response.data;
          data.data.forEach(item => {
            let resourceList = item.resourceList;
            resourceList.forEach(element => {
              let imgUrl = `${config.host}/s/public_data/${element.ghid}/thumb`;
              element.img = imgUrl;
            });
          });

          this.appliedList = data.data;
          this.hasNext = false;
          this.handleScrollbar();
        });
    },
    deleteAppliedRes(params) {
      this.$confirm("确认要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let url = `${config.api}/resourceApply/delete/order/${params.item.applyOrderId}`;
          this.$root.$http.get(url).then(response => {
            console.log(response);
            if (response.data.success) {
              this.appliedList.splice(params.index, 1);
              this.$message.success("删除成功！");
            }
          });
        })
        .catch(() => {});
    },
    handelPraise(item) {
      let url = `${config.api}/resource/praise/add/${item.resId}`;
      this.$root.$http
        .get(url)
        .then(response => {
          console.log(response);
          if (response.data.success) {
            this.$message.success("点赞成功！");
          }
        })
        .catch(() => {
          this.$message.error("点赞失败！");
        });
    },
    switchBannerNav(event) {
      // let currentTarget = event.currentTarget;
      // if(){
      // }
    },
    handleScrollbar() {
      window.addEventListener(
        "resize",
        debounce(() => {
          this.adjustHeight();
        }, 200)
      );
      this.adjustHeight();
    },
    adjustHeight() {
      let documentHeight = this.$el.querySelector(".first-category")
        .offsetHeight;

      let containerDomList = this.$el.querySelectorAll(".el-scrollbar");
      for (let containerDom of containerDomList) {
        containerDom.style.height =
          documentHeight - containerDom.offsetTop - 50 + "px";
      }
    },
    removeResDuplicate(index) {
      this.resDuplicateList.splice(index, 1);
    },
    dataDescribeCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 0) {
        return "font-weight:bold";
      }
    },
    switchMapWidgets(type, event) {
      let currentTarget = event.currentTarget;
      if (currentTarget.classList.contains("active")) {
        return;
      } else {
        this.$el
          .querySelector(".map-bottom-widgets .active")
          .classList.remove("active");
        currentTarget.classList.add("active");
      }
      if (type == "map") {
        this.mapPreviewVisible = true;
        setTimeout(() => {
          this.map && this.map.resize();
        }, 100);
      } else if (type == "metadata") {
        this.mapPreviewVisible = false;
      }
    }
  }
};
</script>

<style src="./resource-center.css" scoped></style>
